package com.yanqu.road.server.logic.recharge;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.log.LogCouponUse;
import com.yanqu.road.entity.player.UserCouponItem;
import com.yanqu.road.entity.recharge.RechargeResult;
import com.yanqu.road.entity.recharge.ThirdPartyRechargeOrder;
import com.yanqu.road.entity.recharge.RechargeOrder;
import com.yanqu.road.entity.enums.eMallCategory;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.banquet.BanquetModule;
import com.yanqu.road.server.gameplayer.module.player.*;
import com.yanqu.road.server.logic.recharge.limit.BaseRMBMallLimit;
import com.yanqu.road.server.logic.recharge.limit.MallLimitFactory;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.MallMgr;
import com.yanqu.road.server.manger.config.MallRechargeConfigMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.thirdparty.ThirdPartyMgr;
import com.yanqu.road.utils.order.OrderHelper;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Date;
import java.util.List;

public abstract class BaseRecharge {

    protected Logger logger = LogManager.getLogger(BaseRecharge.class.getName());
    protected GamePlayer player;
    protected MallInfo mallInfo;
    protected ActivityInfo activityInfo;

    public BaseRecharge(GamePlayer player, MallInfo mallInfo, ActivityInfo activityInfo) {
        this.player = player;
        this.mallInfo = mallInfo;
        this.activityInfo = activityInfo;
    }

    /**
     * 是否重复购买
     */
    protected abstract boolean isRepeatedBuy(String orderNo);

    /**
     *  重复购买需要特殊操作的在这里处理
     */
    protected abstract void repeatedBuyLogic();

    /**
     * 加商品
     */
    protected abstract String addMall(String orderNo, RechargeOrder rechargeOrder);

    /**
     * 充值，返回值标识是否重复购买
     */
    public RechargeResult recharge(String orderNo, List<RechargeOrder> rechargeOrderList, List<ThirdPartyRechargeOrder> thirdPartyOrderList,
                                   boolean isThirdParty, boolean doReturnIngots, RechargeOrder rechargeOrder) {
        RechargeResult rechargeResult = new RechargeResult();
        if(MallMgr.isSubscribeMall(mallInfo.getMallId())){//订阅商品
            if(null != rechargeOrder && !StringUtils.isNullOrEmpty(rechargeOrder.getSubscription())){
                JSONObject dataObj = JSON.parseObject(rechargeOrder.getSubscription());
                int type = dataObj.getIntValue("type");
                String reward = addMall(orderNo, rechargeOrder);
                rechargeResult.setReward(reward);
                if(0 == type || 1 == type){//新订阅，续订
                    //加跨服宴会贴
                    if (mallInfo.getActivityId() > 0) {
                        player.getModule(BanquetModule.class).getCrossBanquetInvitationReward(reward, mallInfo.getActivityId());
                    }
                    logger.info("订阅订单: {},商品 :{} 成功.", orderNo, mallInfo.getMallId());

                    //AttributeModule attributeModule = player.getModule(AttributeModule.class);
                    //long lastRechargeTime = attributeModule.getAttribute(ePlayerAttrType.LastRechargeTime);
                    //首次充值时间
                    //DataAnalyticsMgr.firstPayTime(player, lastRechargeTime);

                    //充值埋点
                    //DataAnalyticsMgr.allRechargeInfo(player);

                    //加vip
                    player.getModule(RechargeModule.class).addRechargeAmount(mallInfo);
                }
            }
        }else {
            String reward = "";
            if(null != rechargeOrder && rechargeOrder.getCouponItemId() > 0){//使用优惠券
                CouponModule couponModule = player.getModule(CouponModule.class);
                UserCouponItem userCouponItem = couponModule.getUserCouponItem(rechargeOrder.getCouponItemId());
                if(null == userCouponItem){
                    if (doReturnIngots) {
                        MallMgr.returnGoldToken(player, mallInfo, rechargeOrder.getCouponGoodsId());
                        repeatedBuyLogic();
                        logger.warn("代金券不存在，代金券id：{}，订单:{}，商品：{}，返还通宝:{}", rechargeOrder.getCouponItemId(), orderNo, mallInfo.getMallId(), MallRechargeConfigMgr.getParamValue(mallInfo));
                    }
                    rechargeResult.setRepeatedBuy(true);
                    return rechargeResult;
                }else {
                    synchronized (userCouponItem){
                        if(userCouponItem.isUse()){
                            if (doReturnIngots) {
                                MallMgr.returnGoldToken(player, mallInfo, userCouponItem.getGoodsId());
                                repeatedBuyLogic();
                                logger.warn("代金券已使用，代金券id：{}，订单:{}，商品：{}，返还通宝:{}", rechargeOrder.getCouponItemId(), orderNo, mallInfo.getMallId(), MallRechargeConfigMgr.getParamValue(mallInfo));
                            }
                            rechargeResult.setRepeatedBuy(true);
                            return rechargeResult;
                        }
                        if(System.currentTimeMillis() > userCouponItem.getExpirationTime()){
                            if (doReturnIngots) {
                                MallMgr.returnGoldToken(player, mallInfo, userCouponItem.getGoodsId());
                                repeatedBuyLogic();
                                logger.warn("代金券已过期，代金券id：{}，订单:{}，商品：{}，返还通宝:{}", rechargeOrder.getCouponItemId(), orderNo, mallInfo.getMallId(), MallRechargeConfigMgr.getParamValue(mallInfo));
                            }
                            rechargeResult.setRepeatedBuy(true);
                            return rechargeResult;
                        }
                        if (needReturnIngots(orderNo, rechargeOrderList, thirdPartyOrderList, isThirdParty)) {//是否返元宝
                            if (doReturnIngots) {
                                MallMgr.returnGoldToken(player, mallInfo, userCouponItem.getGoodsId());
                                repeatedBuyLogic();
                                logger.warn("订单:{} 重复购买: {}, 返还通宝: {}", orderNo, mallInfo.getMallId(), MallRechargeConfigMgr.getParamValue(mallInfo));
                            }
                            rechargeResult.setRepeatedBuy(true);
                            return rechargeResult;
                        }
                        reward = addMall(orderNo, rechargeOrder);
                        userCouponItem.setUse(true);
                        couponModule.addCouponUsedCount();
                        couponModule.syncCoupon(userCouponItem);
                        //上报、加日志
                        int potential = player.getModule(PotentialModule.class).getPotential();
                        String goodsName = GoodsMgr.getLocalGoodsName(userCouponItem.getGoodsId(), player.getLanguage());
                        ThirdPartyMgr.couponReport(player.getUserId(), player.getUserInfo().getPlatformUserId(), userCouponItem.getGoodsId(), goodsName,
                                0, couponModule.getCouponItemTotalCount(), couponModule.getCouponItemCount(), "", "",
                                player.getTitleId(), potential, new Date(), mallInfo.getMallId(), MallMgr.getMallName(mallInfo, player.getLanguage()),
                                rechargeOrder.getRealMoney(), "", new Date());
                        AutoLogMgr.add(new LogCouponUse(player.getUserId(), userCouponItem.getItemId(), userCouponItem.getGoodsId(),
                                couponModule.getCouponItemTotalCount(), couponModule.getCouponItemCount(), player.getTitleId(),
                                mallInfo.getMallId(), rechargeOrder.getRealMoney()));
                    }
                }
            }else {//未使用优惠券
                if (needReturnIngots(orderNo, rechargeOrderList, thirdPartyOrderList, isThirdParty)) {//是否返元宝
                    if (doReturnIngots) {
                        MallMgr.returnGoldToken(player, mallInfo, 0);
                        repeatedBuyLogic();
                        logger.warn("订单:{} 重复购买: {}, 返还通宝: {}", orderNo, mallInfo.getMallId(), MallRechargeConfigMgr.getParamValue(mallInfo));
                    }
                    rechargeResult.setRepeatedBuy(true);
                    return rechargeResult;
                }
                reward = addMall(orderNo, rechargeOrder);
            }
            rechargeResult.setReward(reward);
            //加跨服宴会贴
            if (mallInfo.getActivityId() > 0) {
                player.getModule(BanquetModule.class).getCrossBanquetInvitationReward(reward, mallInfo.getActivityId());
            }
            logger.info("订单: {} 充值 商品 :{} 成功.", orderNo, mallInfo.getMallId());

            //AttributeModule attributeModule = player.getModule(AttributeModule.class);
            //long lastRechargeTime = attributeModule.getAttribute(ePlayerAttrType.LastRechargeTime);
            //首次充值时间
            //DataAnalyticsMgr.firstPayTime(player, lastRechargeTime);

            //充值埋点
            //DataAnalyticsMgr.allRechargeInfo(player);

            //加vip
            player.getModule(RechargeModule.class).addRechargeAmount(mallInfo);
        }
        return rechargeResult;
    }

    //后台充值直接到账
    public void backendRecharge(){
        //订单唯一标识要不一样
        addMall("bn" + OrderHelper.generateOrderNum(), null);
        logger.info("后台 充值 商品 :{} 成功.", mallInfo.getMallId());
    }

    /**
     * 需要返元宝？
     */
    private boolean needReturnIngots(String orderNo, List<RechargeOrder> rechargeOrderList,
                                     List<ThirdPartyRechargeOrder> thirdPartyOrderList, boolean isThirdParty){

        // 是否需要检查mall表限购
        boolean checkMallInfoLimit = true;
        if (mallInfo.getCategory() == eMallCategory.RechargeGoods.getValue() && activityInfo != null) {
            if (activityInfo.getType() == eActivityType.RechargeActivity.getValue() || activityInfo.getType() == eActivityType.NewRechargeActivity.getValue()) {
                checkMallInfoLimit = false;
            }
        }

        if (checkMallInfoLimit) {
            // MallInfo的限购检查
            if (MallMgr.isRechargeLimitBuy(mallInfo, orderNo, rechargeOrderList, thirdPartyOrderList, isThirdParty)) {
                return true;
            }
        }

        BaseRMBMallLimit baseRMBMallLimit = MallLimitFactory.getMallLimit(player.getUserId(), mallInfo, activityInfo);
        if(null == baseRMBMallLimit){
            return true;
        }
        if(0 != baseRMBMallLimit.checkMallLimit().getRet()){
            return true;
        }

        return isRepeatedBuy(orderNo);
    }

    protected void addMall() {
        player.getModule(CurrencyModule.class).addCurrency(PropertyHelper.parseStringToProperty(mallInfo.getReward()),
                eLogMoneyType.Recharge, eLogMoneyType.ReChargeGet);
    }

    public static BaseRecharge getBaseChargeLogic(GamePlayer player, MallInfo mallInfo, ActivityInfo activityInfo) {
        if(null == mallInfo){
            return null;
        }
        if(mallInfo.getCategory() == eMallCategory.Ingots.getValue()){
            return new IngotsRecharge(player, mallInfo, activityInfo);
        }else if(mallInfo.getCategory() == eMallCategory.PrivilegeCard.getValue()){
            return new CardRecharge(player, mallInfo, activityInfo);
        }else if(mallInfo.getCategory() == eMallCategory.Fund.getValue()){
            return new FundRecharge(player, mallInfo, activityInfo);
        }else if(mallInfo.getCategory() == eMallCategory.SecretVolume.getValue()){
            return new SecretVolumeRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.TriggerRMBMall.getValue()) {
            return new TriggerRMBRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.CrossRankRMBMall.getValue()) {
            return new CrossRankRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.HuaShiGangRMBMall.getValue()) {
            return new HuaShiGangRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.FiveHeroRecharge.getValue()) {
            return new FiveHeroRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.DaFuWengRMBMall.getValue()) {
            return new DaFuWengRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.UnionWarRMBMall.getValue()) {
            return new UnionWarRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.ZhanLingGiftBag.getValue()) {
            return new ZhanLingRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.DunHuangShiKuRMBMall.getValue()) {
            return new DunHuangShiKuRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.CookBoy3Bag.getValue()) {
            return new CookBoy3Recharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.CookBoy2Bag.getValue()) {
            return new CookBoy2Recharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.ChefDuel3Bag.getValue()) {
            return new ChefDuel3Recharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.ChefDuel2Bag.getValue()) {
            return new ChefDuel2Recharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.DouLuoDaLuRMBMall.getValue()) {
            return new DouLuoDaLuActivityRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.ReissueMall.getValue()) {
            return new ReissueRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.ChannelRankRMBMall.getValue()) {
            return new ChannelRankRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.ChineseChessToken.getValue()) {
            return new ChineseChessToken(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.TongBingRedPacketMall.getValue()) {
            return new TongbingActivityRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.ChuHanRmbMall.getValue()) {
            return new ChuHanActivityRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.SuiTangMall.getValue()) {
            return new SuiTangActivityRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.RankUnionWarRMBMall.getValue()) {
            return new RankUnionWarRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.RechargeGoods.getValue()) {
            if(null == activityInfo){
                return null;
            }
            if(activityInfo.getType() == eActivityType.RechargeActivity.getValue() ||
                    activityInfo.getType() == eActivityType.NewRechargeActivity.getValue()
            ){
                return new RechargeActivityRecharge(player, mallInfo, activityInfo);
            }
            return null;
        }else if (mallInfo.getCategory() == eMallCategory.PastureToken.getValue()) {
            return new PastureToken(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.GreatTradeCard.getValue()) {
            return new GreatTradeCardRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.GoldTokeMall.getValue()) {
            return new GoldTokenRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.WasheToken.getValue()) {
            return new WasheTokenRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.WasheRmbMall.getValue()) {
            return new WasheRmbMallRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.FlowerCardMall.getValue()) {
            return new FlowerCardActivityRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.OperaMaskToken.getValue()) {
            return new OperaMaskTokenRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.ReturnRoleOnlyPrivilegeCard.getValue()) {
            return new ReturnRoleCardRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.ReturnRmbMall.getValue()) {
            return new ReturnRoleRmbMallRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.CricketCourtToken.getValue()) {
            return new CricketCourtTokenRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.WasheRmbMallDirect.getValue()) {
            return new WasheDirectRmbMallRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.QixiRecharge.getValue()) {
            return new QixiRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.FestivalGift.getValue()) {
            return new FestivalGiftMallRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.TenDaysDiscountMall.getValue()){
            return new TenDayDiscountMallRecharge(player, mallInfo, activityInfo);
        }else if (mallInfo.getCategory() == eMallCategory.EveFeastToken.getValue()) {
            return new EveFeastToken(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.TongBaoRecharge.getValue()){
            return new TongBaoRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.PatronsFund.getValue()) {
            return new PatronsFundMallRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.JinLi.getValue()) {
            return new JinLiRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.SteleSoul.getValue()){
            return new SteleSoulRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.NewFirstRechargeCash.getValue()) {
            return new NewFirstRechargeCashRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.NewFirstRecharge2024.getValue()) {
            return new NewFirstRecharge2024Recharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.JiuZhou.getValue()){
            return new JiuZhouRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.SnowGardenToken.getValue() || mallInfo.getCategory() == eMallCategory.SummerGamesFound.getValue() || mallInfo.getCategory() == eMallCategory.ApprenticeFund.getValue()) {
            return new SnowGardenTokenRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.ServerAllBuyMall.getValue()||mallInfo.getCategory() == eMallCategory.ServerAllSecondBuyMall.getValue() || mallInfo.getCategory() == eMallCategory.SummerGamesAllMall.getValue() || mallInfo.getCategory() == eMallCategory.ApprenticeTgMall.getValue()) {
            return new ServerBuyRmbMallRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.SystemOpenTriggerRMBMall.getValue()) {
            return new SystemOpenTriggerRMBRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.DoubleSpringZlMallZl.getValue()) {
            return new DoubleSpringZlRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.DoubleSpringZlMallHelp.getValue()) {
            return new DoubleSpringHelpRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.ZhenHuanThirdProcessRecharge.getValue()) {
            return new ZhenHuanThirdProcessRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.BiaoJu.getValue()) {
            return new BiaoJuRMBRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.SonHaiZl.getValue()) {
            return new SonHaiZlRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.SonHaiGift.getValue()) {
            return new SonHaiGiftRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.HsIslandZl.getValue()) {
            return new HsIslandZlRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.CombLeaderFund.getValue()) {
            return new CombLeaderFundRMBRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.HorseRun.getValue()) {
            return new HorseRunTokenRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.GoldIngotFund.getValue()) {
            return new GoldIngotFundRMBRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.HotpotJump.getValue()) {
            return new HotpotJumpToken(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.StarLight.getValue()) {
            return new StarLightRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.WealthScrollBuyToken.getValue()) {
            return new WealthScrollRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.NewPatronFund.getValue()) {
            return new NewPatronsFundMallRecharge(player, mallInfo, activityInfo);
        } else if (mallInfo.getCategory() == eMallCategory.IceServerGift.getValue()) {
            return new IceServerGiftRecharge(player, mallInfo, activityInfo);
        } else {
            return new NormalRecharge(player, mallInfo, activityInfo);
        }
    }

}
